package com.cheyun.netsalev3.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.text.TextPaint
import android.util.TypedValue
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.cheyun.netsalev3.adapter.TitleAdapter

/**
 * 字母快速选择
 * @author Michael
 * @date  2018/12/24 - 13:56.
 */

class AZTitleDecoration(private val mTitleAttributes: TitleAttributes) : RecyclerView.ItemDecoration() {

    private val mTitleTextPaint: TextPaint = TextPaint()
    private val mBackgroundPaint: Paint

    private var linesPaint: Paint

    init {
        mTitleTextPaint.isAntiAlias = true
        mTitleTextPaint.textSize = mTitleAttributes.mTextSize.toFloat()
        mTitleTextPaint.color = mTitleAttributes.mTextColor
        mBackgroundPaint = Paint()
        mBackgroundPaint.isAntiAlias = true
        mBackgroundPaint.color = mTitleAttributes.mBackgroundColor
        linesPaint = Paint()
        linesPaint.isAntiAlias = true
        linesPaint.color = Color.parseColor("#ffb8bec9")

    }

    /**
     * 绘制标题
     */
    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDraw(c, parent, state)
        if (parent.adapter == null || parent.adapter !is TitleAdapter<*>) {
            return
        }
        val adapter = parent.adapter as TitleAdapter<*>
        if (adapter.temlist == null || adapter.temlist!!.isEmpty()) {
            return
        }
        for (i in 0 until parent.childCount) {
            val child = parent.getChildAt(i)
            val position = parent.getChildAdapterPosition(child)
            if (titleAttachView(child, parent)) {
                drawTitleItem(c, parent, child, adapter.getSortLetters(position)!!)
            }
        }
    }

    /**
     * 绘制悬浮标题
     */
    override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDrawOver(c, parent, state)
        if (parent.adapter == null || parent.adapter !is TitleAdapter<*>) {
            return
        }
        val adapter = parent.adapter as TitleAdapter<*>
        if (adapter.temlist == null || adapter.temlist!!.isEmpty()) {
            return
        }
        val firstView = parent.getChildAt(0)
        val firstAdapterPosition = parent.getChildAdapterPosition(firstView)
        c.save()
        //找到下一个标题对应的adapter position
        val nextLetterAdapterPosition = adapter.getNextSortLetterPosition(firstAdapterPosition)
        if (nextLetterAdapterPosition != -1) {
            //下一个标题view index
            val nextLettersViewIndex = nextLetterAdapterPosition - firstAdapterPosition
            if (nextLettersViewIndex < parent.childCount) {
                val nextLettersView = parent.getChildAt(nextLettersViewIndex)
                val params = nextLettersView.layoutParams as RecyclerView.LayoutParams
                val nextToTop = nextLettersView.top - params.bottomMargin - parent.paddingTop
                if (nextToTop < mTitleAttributes.mItemHeight * 2) {
                    //有重叠
                    c.translate(0f, (nextToTop - mTitleAttributes.mItemHeight * 2).toFloat())
                }
            }
        }
        mBackgroundPaint.color = mTitleAttributes.mBackgroundColor
        linesPaint.color = mTitleAttributes.linesColor
        c.drawRect(parent.paddingLeft.toFloat(), parent.paddingTop.toFloat(), (parent.right - parent.paddingRight).toFloat(),
                (parent.paddingTop + mTitleAttributes.mItemHeight).toFloat(), mBackgroundPaint)
        mTitleTextPaint.textSize = mTitleAttributes.mTextSize.toFloat()
        mTitleTextPaint.color = mTitleAttributes.mTextColor
        if (adapter.getSortLetters(firstAdapterPosition) == "★") {
            mTitleTextPaint.color = Color.parseColor("#FF52D5E9")
            //绘制标题文字
            c.drawText(adapter.getSortLetters(firstAdapterPosition),
                    (parent.paddingLeft + firstView.paddingLeft + mTitleAttributes.mTextPadding).toFloat(),
                    TextDrawUtils.getTextBaseLineByCenter(parent.paddingTop + mTitleAttributes.mItemHeight / 2, mTitleTextPaint),
                    mTitleTextPaint)
            mTitleTextPaint.color = mTitleAttributes.mTextColor
            c.drawText("    常用品牌",
                    (parent.paddingLeft + firstView.paddingLeft + mTitleAttributes.mTextPadding).toFloat(),
                    TextDrawUtils.getTextBaseLineByCenter(parent.paddingTop + mTitleAttributes.mItemHeight / 2, mTitleTextPaint),
                    mTitleTextPaint)
        } else {
            //绘制标题文字
            c.drawText(adapter.getSortLetters(firstAdapterPosition),
                    (parent.paddingLeft + firstView.paddingLeft + mTitleAttributes.mTextPadding).toFloat(),
                    TextDrawUtils.getTextBaseLineByCenter(parent.paddingTop + mTitleAttributes.mItemHeight / 2, mTitleTextPaint),
                    mTitleTextPaint)
        }
        //绘制线
        c.drawLine(parent.paddingLeft.toFloat(), (parent.paddingTop + mTitleAttributes.mItemHeight).toFloat(),
                (parent.width - parent.paddingRight).toFloat(), (parent.paddingTop + mTitleAttributes.mItemHeight).toFloat(), linesPaint)
        c.restore()
    }

    /**
     * 设置空出绘制标题的区域
     */
    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        if (titleAttachView(view, parent)) {
            if (parent.getChildAdapterPosition(view) == 0) {
                outRect.set(0, mTitleAttributes.mItemHeight, 0, 0)
            } else {
                outRect.set(0, mTitleAttributes.mItemHeight + mTitleAttributes.mItemMarginTop, 0, 0)
            }
        } else {
            super.getItemOffsets(outRect, view, parent, state)
        }
    }

    /**
     * 绘制标题信息
     */
    private fun drawTitleItem(c: Canvas, parent: RecyclerView, child: View, letters: String) {
        val params = child.layoutParams as RecyclerView.LayoutParams
        //绘制背景
        c.drawRect(parent.paddingLeft.toFloat(), (child.top - params.bottomMargin - mTitleAttributes.mItemHeight).toFloat(),
                (parent.width - parent.paddingRight).toFloat(), (child.top - params.bottomMargin).toFloat(), mBackgroundPaint)

        val textCenterY = child.top - params.bottomMargin - mTitleAttributes.mItemHeight / 2
        if (letters == "★") {
            //绘制标题文字
            c.drawText(letters, (parent.paddingLeft + child.paddingLeft + mTitleAttributes.mTextPadding).toFloat(),
                    TextDrawUtils.getTextBaseLineByCenter(textCenterY, mTitleTextPaint), mTitleTextPaint)
            //绘制标题文字
            c.drawText("常用品牌", (parent.paddingLeft + child.paddingLeft + mTitleAttributes.mTextPadding).toFloat(),
                    TextDrawUtils.getTextBaseLineByCenter(textCenterY, mTitleTextPaint), mTitleTextPaint)
        } else {
            //绘制标题文字
            c.drawText(letters, (parent.paddingLeft + child.paddingLeft + mTitleAttributes.mTextPadding).toFloat(),
                    TextDrawUtils.getTextBaseLineByCenter(textCenterY, mTitleTextPaint), mTitleTextPaint)
        }

        //绘制线
        c.drawLine(parent.paddingLeft.toFloat(), (child.top - params.bottomMargin).toFloat(),
                (parent.width - parent.paddingRight).toFloat(), (child.top - params.bottomMargin).toFloat(), linesPaint)


    }

    /**
     * 判断指定view的上方是否要空出绘制标题的位置
     *
     * @param view   　指定的view
     * @param parent 父view
     */
    private fun titleAttachView(view: View, parent: RecyclerView): Boolean {
        if (parent.adapter == null || parent.adapter !is TitleAdapter<*>) {
            return false
        }
        val adapter = parent.adapter as TitleAdapter<*>
        if (adapter.temlist == null || adapter.temlist!!.isEmpty()) {
            return false
        }
        val position = parent.getChildAdapterPosition(view)

        //第一个一定要空出区域 + 每个都和前面一个去做判断，不等于前一个则要空出区域
        return position == 0 || null != adapter.temlist!![position] && !adapter.getSortLetters(position).equals(adapter.getSortLetters(position - 1))

    }

    class TitleAttributes(internal var mContext: Context) {
        /**
         * 标题高度
         */
        internal var mItemHeight: Int = 0
        /**
         * 标题margintop高度
         */
        internal var mItemMarginTop: Int = 0
        /**
         * 文字的padding
         */
        internal var mTextPadding: Int = 0
        /**
         * 标题文字大小
         */
        internal var mTextSize: Int = 0
        /**
         * 标题文字颜色
         */
        internal var mTextColor: Int = 0
        internal var linesColor: Int = 0
        /**
         * 标题背景
         */
        internal var mBackgroundColor: Int = 0

        init {
            mItemHeight = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30f, mContext.resources.displayMetrics).toInt()
            mTextPadding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8f, mContext.resources.displayMetrics).toInt()
            mTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 14f, mContext.resources.displayMetrics).toInt()
            mTextColor = Color.parseColor("#FF000000")
            mBackgroundColor = Color.parseColor("#FFDFDFDF")
        }

        fun setItemHeight(heightDp: Int): TitleAttributes {
            mItemHeight = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, heightDp.toFloat(),
                    mContext.resources.displayMetrics).toInt()
            return this
        }

        fun setItemMarginTop(margintop: Int): TitleAttributes {
            mItemMarginTop = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, margintop.toFloat(),
                    mContext.resources.displayMetrics).toInt()
            return this
        }

        fun setTextPadding(paddingDp: Int): TitleAttributes {
            mTextPadding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, paddingDp.toFloat(),
                    mContext.resources.displayMetrics).toInt()
            return this
        }

        fun setTextSize(sizeSp: Int): TitleAttributes {
            mTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sizeSp.toFloat(), mContext.resources.displayMetrics).toInt()
            return this
        }

        fun setTextColor(color: Int): TitleAttributes {
            mTextColor = color
            return this
        }

        fun setBackgroundColor(color: Int): TitleAttributes {
            mBackgroundColor = color
            return this
        }

        fun setLineColor(color: Int): TitleAttributes {
            linesColor = color
            return this
        }


    }
}
